package com.example.OJ.compile;

import com.example.OJ.utils.FileUtil;

import java.io.File;
import java.util.UUID;

//每次编译+运行就是一个Task
public class Task {

    //
    private String WORK_DIR = "./tmp/";
    //
    private String CLASS = null;
    //
    private String CODE = null;
    private String COMPILE_ERROR = null;
    private String STDOUT = null;
    private String STDERR = null;

    public Task(){
        WORK_DIR += UUID.randomUUID().toString()+"/";
        CLASS = "Solution";
        CODE = WORK_DIR+"Solution.java";
        COMPILE_ERROR = WORK_DIR + "compileError.txt";
        STDOUT = WORK_DIR+"stdout.txt";
        STDERR = WORK_DIR+"stderr.txt";
    }

    public Answer compileAndRun(Question question){
        Answer answer = new Answer();
        //1、准备用来存放临时文件的目录
        File workDir = new File(WORK_DIR);
        if(!workDir.exists()){
            //创建多级目录
            workDir.mkdirs();
        }
        //2、将question中的 code写入到一个Solution.java中
        FileUtil.writeFile(CODE,question.getCode());

        //3、创建子进程 调用javac进行编译(确保有Solution.java)
        //   一旦出错，错误信息会写入到stderr里
        //   javac只关注标准错误，这个进程只是用来编译！
        System.out.println(String.format("javac -encoding utf8 %s -d %s",CODE,WORK_DIR));
        String compileCmd = String.format("javac -encoding utf8 %s -d %s",CODE,WORK_DIR);

        CommandUtil.run(compileCmd,null,COMPILE_ERROR);
        String compileError = FileUtil.readFile(COMPILE_ERROR);
        if(!compileError.equals("")){
            //error
            answer.setError(1);
            answer.setReason(compileError);
            return answer;
        }
        //4、创建子进程 调用java进行执行
        String runCmd = String.format("java -classpath %s %s",WORK_DIR,CLASS);
        System.out.println(runCmd);
        CommandUtil.run(runCmd,STDOUT,STDERR);
        String runError = FileUtil.readFile(STDERR);
        String runOut = FileUtil.readFile(STDOUT);
        if(!runError.equals("")){
            answer.setError(2);
            answer.setReason(runError);
            return answer;
        }

        answer.setError(0);
        answer.setStdout(runOut);
        return answer;
    }

    public static void main(String[] args) {
        Task task = new Task();
        Question question = new Question();
        question.setCode(
                "public class Solution\n" +
                "{\n" +
                "    public static void main(String[] args) {\n" +
                "        System.out.println(\"hello world!\");\n" +
                "    }\n" +
                "}\n");
        Answer answer = task.compileAndRun(question);
        System.out.println(answer);
    }
}

